package com.beaven.model.data.helper;

import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.api.message.MsgCreateModel;
import com.beaven.model.model.card.MessageCard;
import com.beaven.model.model.db.Message;
import com.beaven.model.model.db.Message_Table;
import com.beaven.model.model.db.User;
import com.beaven.model.net.HTTPService;
import com.beaven.model.net.NetFactory;
import com.raizlabs.android.dbflow.sql.language.OperatorGroup;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/6/1 10:53
 */

public class MessageHelper {

  public static Observable<RspModel<MessageCard>> push(MsgCreateModel model) {
    HTTPService service = NetFactory.getService();
    return service.msgPush(model)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
  }

  // 从本地找消息
  public static Message findFromLocal(String id) {
    return SQLite.select().from(Message.class).where(Message_Table.id.eq(id)).querySingle();
  }

  public static User findSenderId(String msgId) {
    Message message =
        SQLite.select().from(Message.class).where(Message_Table.id.eq(msgId)).querySingle();
    User user = null;
    if (message != null) {
      message.load();
      user = message.getSender();
      user = UserHelper.findById(user.getId());
    }
    return user;
  }

  /**
   * 查询一个消息，这个消息是一个群中的最后一条消息
   *
   * @param groupId 群Id
   * @return 群中聊天的最后一条消息
   */
  public static Message findLastWithGroup(String groupId) {
    return SQLite.select()
        .from(Message.class)
        .where(Message_Table.receiveGroup_id.eq(groupId))
        .orderBy(Message_Table.createAt, false) // 倒序查询
        .querySingle();
  }

  /**
   * 查询一个消息，这个消息是和一个人的最后一条聊天消息
   *
   * @param userId UserId
   * @return 聊天的最后一条消息
   */
  public static Message findLastWithUser(String userId) {
    return SQLite.select()
        .from(Message.class)
        .where(OperatorGroup.clause()
            .and(Message_Table.sender_id.eq(userId))
            .and(Message_Table.receiveGroup_id.isNull()))
        .or(Message_Table.receiver_id.eq(userId))
        .orderBy(Message_Table.createAt, false) // 倒序查询
        .querySingle();
  }
}
